var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
	res.send('<h1>Welcome Realtime Server</h1>');
});

//在线用户
var onlineUsers = {};
//当前在线人数
var onlineCount = 0;

var guid = 1;
function getnewguid(){
	var nguid = 0xffffffff&guid;
	guid++;
	return nguid; 
}

function newuser(){
	return {
		info:{},
		roles:[],
		equips:{},
		cards:{},
	}
}

io.on('connection', function(socket){
	socket.name = getnewguid();
	console.log('a user connected:'+socket.name);
	var u = newuser();
	u.info.name = socket.name;
	onlineUsers[socket.name] = u;
	
	//监听新用户加入
	socket.on('login', function(obj){
		console.log('login msg');
		if(obj.name != obj.pass){
			socket.emit('login',{success:false,info:'password invalid!'});
			return;
		}
		var u = onlineUsers[socket.name];
		// 删除临时数据
		delete onlineUsers[socket.name];
		//将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
		socket.name = obj.name;
		u.info.name = obj.name;
		onlineUsers[socket.name] = u;
		
		//检查在线列表，如果不在里面就加入
		if(!onlineUsers.hasOwnProperty(obj.name)) {
			onlineUsers[obj.name] = obj.name;
			//在线人数+1
			onlineCount++;
		}

		socket.emit('login',{success:true,info:u.info,roles:u.roles});
		
	});

	// 创建角色
	socket.on('newrole',function(obj){
		var u = onlineUsers[socket.name];
		var r = {};
		r.hp = 10;
		r.mp = 1;
		r.atk = 1;
		r.roleid = obj.id;
		r.id = getnewguid();
		u.roles.push(r);

		socket.emit('newrole',{success:true,role:r}); 
	});
	
	//监听用户退出
	socket.on('disconnect', function(){
		console.log('a user disconnected:'+socket.name);
		//将退出的用户从在线列表中删除
		if(onlineUsers.hasOwnProperty(socket.name)) {			
			//删除
			delete onlineUsers[socket.name];
			//在线人数-1
			onlineCount--;
		}
	});  
});

http.listen(3000, function(){
	console.log('listening on *:3000');
});